package com.cyan.teamquestionnaire.utils;

import org.apache.http.HttpResponse;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MessageUtils {

    private static void sendMessage(String code, String tel) {
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "c2e870c775554194996bdb18cafd0463";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> query = new HashMap<String, String>();
        Map<String, String> body = new HashMap<String, String>();
        body.put("content", "code:" + code);
        body.put("phone_number", "" + tel + "");
        body.put("template_id", "TPL_0000");

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, query, body);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 传入手机号发送短信
    public static void execute(String tel, RedisTemplate<String, Object> redisTemplate) {
        StringBuffer sb = new StringBuffer();
        // 生成6位验证码
        for (int i = 0; i < 6; i++) sb.append((int) (Math.random() * 10));
        //设置redis的key，这里设置为项目名:使用的字段:用户电话号
        String redisKey = "VERIFATIONCODE:CODE:" + tel;
        //将这个验证码存入redis中，并设置失效时间
        redisTemplate.opsForValue().set(redisKey, sb.toString(), 300, TimeUnit.SECONDS);
//        sendMessage(sb.toString(), phoneNum);// 发送短信
    }
}
